package com.squid.base.config.filter;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.squid.base.config.wrapper.BodyReaderHttpServletRequestWrapper;
import com.squid.base.utils.HttpRequestUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartResolver;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * Description
 *
 * @author jinhang
 * @since 2024-3-7
 **/
@Slf4j
public class HttpRequestLogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = HttpRequestUtils.getHttpServletRequest(servletRequest);
            String contentType = request.getContentType();
            if (StringUtils.isNotBlank(contentType)) {
                //是否是json
                if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE) || contentType.startsWith(MediaType.APPLICATION_XML_VALUE)) {
                    requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) servletRequest);
                    log.info("请求地址：{},接口传入参数:{}", request.getRequestURI(), IoUtil.read(requestWrapper.getInputStream(), StandardCharsets.UTF_8));
                    filterChain.doFilter(requestWrapper, servletResponse);
                    return;
                } else {
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    log.info("请求地址：{}", request.getRequestURI());
                    parameterMap.forEach((x, y) -> {
                        log.info("入参名称：{}-------参数值：{}", x, y);
                    });
                }
            }
            filterChain.doFilter(request, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }


}
